package com.emspost.utils;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPUtil {
    public static void main(String[] args) {
        // 替换文件路径
        String filePath = "/Users/yugan/code/untitled/src/main/resources/ip_addr.txt";
        TreeSet<String> subnets = new TreeSet<>();

        // 匹配有效IPv4地址的正则表达式
        Pattern ipPattern = Pattern.compile(
                "\\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}" +
                        "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b"
        );

        try {
            Files.lines(Paths.get(filePath)).forEach(line -> {
                Matcher matcher = ipPattern.matcher(line);
                while (matcher.find()) {
                    String ip = matcher.group();
                    String[] octets = ip.split("\\.");
                    if (octets.length == 4) {
                        String subnet = String.format("%s.%s.%s.0/24",
                                octets[0], octets[1], octets[2]);
                        subnets.add(subnet);
                    }
                }
            });
        } catch (IOException e) {
            System.err.println("读取文件时发生错误: " + e.getMessage());
            return;
        }

        // 输出排序后的结果
//        System.out.println("生成的子网列表：");
        subnets.forEach(System.out::println);
    }

}
